from django.shortcuts import render, redirect
from django.http import Http404
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.conf import settings
from . import models


def home(request, page_no=1):
    """  首页  文章列表 """
    page_num = settings.PAGE_NUM
    context = {}

    # 第一页 [0:2]  第二页[2,2]
    _limit_start = (page_no-1) * page_num
    _limit_end = page_no * page_num

    # select * from blog_article order by pub_time desc limit 0, 2;
    article_list = models.Article.objects.all().order_by('-pub_time')[_limit_start:_limit_end]

    # 如果对前端取值语法疑惑，可以后端先打印
    # article_list[0].tags.all()

    # 使用原始sql写
    # for article in article_list:
    #     article_list.append({
    #         'title': article.title,
    #         'content': article.content,
    #         'category': article.category.name,  # select * from blog_category where id=%s' %article['category_id']
    #         'tags': []  # select * blog_article_tag where article_id=1; 循环tagsid, select name from blog_tag where id=tagid;
    #     })

    context['article_list'] = article_list
    context['page_no'] = page_no
    return render(request, 'home.html', context=context)

def detail(request, id):

    print(id)
    # pass